package com.filepd.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler implements AuthenticationFailureHandler {


    /**
     * 登录用户名或密码不正确的403处理方法
     * @param bx
     */
    @ExceptionHandler({BadCredentialsException.class})
    public R<String> exceptionHandler(BadCredentialsException bx) {
        log.error(bx.getMessage());
        return R.error("用户名或密码错误");
    }

    /**
     * 登录时账号不对的异常处理方法
     *
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public R<String> exceptionHandler(RuntimeException rx) {

        LocalDateTime now = LocalDateTime.now(); // 获取当前时间

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        log.info("异常时间点 : " + formattedDateTime);
        log.error(rx.getMessage());
        if (rx.getMessage().contains("用户名或密码错误")) {
            return R.error("用户名或密码错误");
        } else if (rx.getMessage().contains("不允许访问")) {
            return R.error("权限不足,不允许访问: " + formattedDateTime);
        }else if(rx.getMessage().contains("Source must not be null")){
            return  R.error("没找到数据,请检查ID等等: " + formattedDateTime);
        }else if(rx.getMessage().contains("此地区方案为空")){
            return R.error("此地区方案为空");
        }else if(rx.getMessage().contains("此地区帖子为空")){
            return R.error("此地区帖子为空");
        }
        return R.error("没预料的异常,请联系管理员: "+ formattedDateTime);
    }


    /**
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // String errorMessage = "用户名或密码不正确";
        //
        // // 如果是账户被锁定或禁用了，则提供不同的错误信息
        // if (exception instanceof LockedException) {
        //     errorMessage = "账户已被锁定，请联系管理员";
        // } else if (exception instanceof DisabledException) {
        //     errorMessage = "账户已被禁用，请联系管理员";
        // }
        //
        // // 返回 JSON 格式的错误信息给前端
        // response.setStatus(HttpStatus.UNAUTHORIZED.value());
        // response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // response.setCharacterEncoding("UTF-8");
        // ObjectMapper mapper = new ObjectMapper();
        // mapper.writeValue(response.getWriter(), errorMessage);
    }
}
